<template>
    <div class="list" :style="list" ref="wrapper">
      <div>
      <div class="current">
        <p class="flag border-topbottom">当前城市</p>
        <div class="item">
          <div><div class="button">{{ this.cityName }}</div></div>
        </div>
      </div>
      <div class="hot">
        <p class="flag border-topbottom">热门城市</p>
        <div class="item">
          <div v-for="item in hotCities" :key="item.id" @click="mainCity">
            <div class="button">{{ item.name }}</div>
          </div>
        </div>
      </div>
      <div class="all">
        <div v-for="(item,key) in cities" :key="key" :ref="key">
          <p class="flag border-topbottom">{{ key }}</p>
          <div class="item">
            <div v-for="val in item" :key="val.id" class="item-border-button" @click="mainCity">
              {{ val.name }}
            </div>
          </div>
        </div>
      </div>
      </div>
    </div>
</template>

<script>
import Bscroll from 'better-scroll'
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'List',
  data () {
    return {
      list: {display: 'black'}
    }
  },
  computed: {
    // vuex 自带的 state 映射
    ...mapState(['cityName'])
  },
  methods: {
    // vuex 自带的 mutations 映射
    ...mapMutations(['updateCityName']),
    mainCity (e) {
      let cityName = e.target.innerText
      // this.store.commit('updateCityName', cityName)
      this.updateCityName(cityName)
      // 当更换城市地址后跳转到首页
      this.$router.push({ path: '/' })
      // 将更改的城市名字保存到本地持久化
      localStorage.setItem('cityName', cityName)
    }
  },
  props: ['hotCities', 'cities', 'letter'],
  mounted () {
    // 移动端页面滚动 overflow: hidden
    this.scroll = new Bscroll(this.$refs.wrapper)
  },
  watch: {
    'letter': function () {
      if (this.letter) {
        // 点击的哪个字母就获取这个字母所在的dom元素
        const element = this.$refs[this.letter][0]
        // console.log(element)
        // 翻滚到指定dom元素的位置
        this.scroll.scrollToElement(element, 100)
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
  .border-topbottom
    &:before
      border-color: #ccc
    &:after
      border-color: #ccc
  .list
    overflow: hidden
    position: absolute
    top: 1.58rem
    left: 0
    right: 0
    bottom: 0
  .flag
    line-height:.54rem
    background-color: #eee
    padding-left: .2rem
    color: #666
  .item
    padding:.1rem .6rem .1rem .1rem
    overflow: hidden
  .item > div
    width:33.33%
  .item > div > .button
    text-align center
    border-radius .06rem
    border 1px solid #cccccc
    margin:.1rem
    padding: .1rem 0
    box-sizing border-box
  .hot > .item > div
    float: left
  .item > .item-border-button
    padding-left: .2rem
    line-height:.76rem
    width:100%
    border-bottom 1px solid #ccc
  .all
    overflow: hidden
  .all  .item
    padding:0
</style>
